<!-- 收费标准管理 -->
<template>
	<!-- 面包屑区 -->
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item :to="{ path: '/counselorInfo' }">咨询师信息管理</el-breadcrumb-item>
		<el-breadcrumb-item>收费标准管理</el-breadcrumb-item>
	</el-breadcrumb>
	<!-- 查询 -->
	<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
		<el-form-item label="咨询师姓名">
			<el-input v-model="queryInfo.consultantName" placeholder="请输入咨询师姓名" clearable />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="queryDataList">搜索</el-button>
			<el-button type="primary" @click="add"> 新增收费标准</el-button>
			<el-button type="danger" @click="batchRemove"> 批量删除</el-button>
		</el-form-item>
	</el-form>
	<!-- 对话框 -->
	<el-dialog :title="title" v-model="dialogFormVisible" width="950" @close="cancle">
		<el-form :model="counselorData" label-width="100">
			<el-form-item label="收费分类">
				<el-select v-model="counselorData.chargeSortName" placeholder="请选择收费分类" style="width: 200px;">
					<el-option v-for="item in options" :label="item.sortName" :value="item.sortName" />
				</el-select>
			</el-form-item>
			<el-form-item label="收费价格">
				<el-input v-model="counselorData.chargePrice" placeholder="请输入收费价格" clearable />
			</el-form-item>
			<el-form-item label="咨询师">
				<el-select v-model="counselorData.consultantName" placeholder="请选择咨询师" style="width: 200px;">
					<el-option v-for="item in choose" :label="item.consultantName" :value="item.consultantName" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取 消</el-button>
				<el-button type="primary" @click="confirm">确 定</el-button>
			</div>
		</template>
	</el-dialog>
	<!-- 展示表格-->
	<el-table :data="dataList" row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
		<el-table-column fixed="left" :data-="dataList" type="selection" width="55" />
		<el-table-column fixed="left" property="id" label="ID" width="60" />
		<el-table-column property="chargeSortName" label="收费分类类别" />
		<el-table-column property="chargePrice" label="收费价格" />
		<el-table-column property="consultCount" label="咨询数量" />
		<el-table-column property="consultantName" label="咨询师姓名" />
		<el-table-column fixed="right" label="操作" min-width="120">
			<template #default="scope">
				<el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
				<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>
	<!-- 书页组件 -->
	<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5,10,15,20]"
		:size="size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
		@current-change="handleCurrentChange" />


	<router-view></router-view>
</template>

<script lang="ts" setup>
	import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
	import { ElMessage, ElMessageBox } from 'element-plus'
	import { Plus } from '@element-plus/icons-vue'
	import type { UploadProps, UploadUserFile } from 'element-plus'


	const pageSize = ref(5);
	const currentPage = ref(1);
	const size = ref('default');


	const queryInfo = reactive({
		id: '',
		chargeSort: '',
		consultantId: '',
		consultantName: '',
		chargePrice: '',
		consultCount: '',
		del: 0,
		pageNum: 1,
		pageSize: 5
	})

	const queryclass = reactive({
		sortName: '',
		id: '',
		del: 0
	});

	const querycounselor = reactive({
		consultantName: '',
		level: null,
		consultantTel: '',
		consultantEmail: '',
		consultantPic: '',
		consultantSex: "",
		consultantCert: '',
		consultantAddress: "",
		consultantDes: '',
		consultantPos: "",
		consultantLevel: null,
		id: "",
		del: 0
	})

	const total = ref(0);
	const dataList = ref([]);
	const options = ref([]);
	const choose = ref([]);

	const axios = getCurrentInstance().appContext.config.globalProperties.axios;
	// // 查询数据
	// 查询数据
	const queryDataList = () => {
		axios.get(`/chargeStandard/page`, {
			params: queryInfo,
		}).then((res) => {
			if (!res || !Array.isArray(res.list)) {
				dataList.value = [];
				total.value = 0;
				ElMessage.error("数据加载失败");
				return;
			}
			dataList.value = res.list.map(item => ({
				id: item.id,
				// 从关联对象 chargeSortObj 中取 sortName 作为分类名称
				chargeSortName: item.chargeSortObj?.sortName || item.chargeSortName,
				chargePrice: item.chargePrice,
				consultCount: item.consultCount,
				// 咨询师名称仍从 consultant 关联对象取（假设字段正确）
				consultantName: item.consultant?.consultantName || item.consultantName,
				del: item.del ?? 0
			}));
			total.value = res.total || 0;
		}).catch(Error => {
			ElMessage.error("查询失败");
		});
	};
	const fetchOptions = () => {
		axios.get(`/chargeSort`)
			.then((res) => {
				console.log('收费分类接口响应:', res); // 确认是纯数组

				let classifyList = [];
				// 处理纯数组响应（后端直接返回数据）
				if (Array.isArray(res)) {
					classifyList = res;
				} else {
					// 兼容单条数据（转为数组）
					classifyList = [res];
				}

				// 映射为前端需要的格式（id + sortName）
				options.value = classifyList.map(item => ({
					id: item.id,
					sortName: item.sortName,
					del: item.del
				}));
			})
			.catch(error => {
				console.error('获取分类数据失败:', error);
				ElMessage.error('分类数据请求失败: ' + error.message);
			});
	};
	const chooseOptions = () => {
		axios.get(`/consultant`)
			.then((res) => {
				console.log('咨询师接口响应:', res); // 确认是纯数组

				let counselorList = [];
				// 处理纯数组响应（后端直接返回数据）
				if (Array.isArray(res)) {
					counselorList = res;
				} else {
					// 兼容单条数据（转为数组）
					counselorList = [res];
				}

				// 映射为前端需要的格式（id + consultantName）
				choose.value = counselorList.map(item => ({
					id: item.id,
					consultantName: item.consultantName,
					level: item.level,
					del: item.del
				}));
			})
			.catch(error => {
				console.error('获取咨询师数据失败:', error);
				ElMessage.error('咨询师数据请求失败: ' + error.message);
			});
	};
	//存储复选的数据
	const multipleSelection = ref([])

	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => {
			return item.id
		})

	}
	//每页显示条目数改变
	const handleSizeChange = (val) => {
		queryInfo.pageSize = val;
		queryDataList();
	}
	//页码改变
	const handleCurrentChange = (val) => {
		queryInfo.pageNum = val;
		queryDataList();
	}

	const title = ref('')
	// 控制对话框是否显示
	const dialogFormVisible = ref(false)

	// 新增和修改数据
	const counselorData = ref({
		id: null,                  // 收费标准ID
		chargeSort: null,          // 收费分类ID（外键）
		chargeSortName: '',        // 收费分类名称（显示用）
		chargePrice: null,         // 收费价格
		consultCount: null,        // 咨询次数
		consultantId: null,        // 咨询师ID
		consultantName: '',        // 咨询师姓名（显示用）
		del: 0
	})


	const cancle = () => {
		counselorData.value = {
			id: null,                  // 收费标准ID
			chargeSort: null,          // 收费分类ID（外键）
			chargeSortName: '',        // 收费分类名称（显示用）
			chargePrice: null,         // 收费价格
			consultCount: null,        // 咨询次数
			consultantId: null,        // 咨询师ID
			consultantName: '',        // 咨询师姓名（显示用）
			del: 0

		}
		dialogFormVisible.value = false
	}
	//组件加载完毕，查询数据
	onMounted(() => {
		queryDataList(); // 加载表格数据
		fetchOptions(); // 加载收费分类数据
		chooseOptions(); // 加载咨询师数据
	});
	
	const confirm = () => {
		// 查找选中的咨询师和分类的ID
		// 查找选中的分类ID（修正：分类的匹配字段是sortName）
		const selectedClassify = options.value.find(item => item.sortName === counselorData.value.chargeSortName);
		// 查找选中的咨询师ID（修正：匹配consultantName字段）
		const selectedCounselor = choose.value.find(item => item.consultantName === counselorData.value.consultantName);
		if (selectedClassify) {
			counselorData.value.chargeSort = selectedClassify.id; // 修改为chargeSort
		}
		if (selectedCounselor) {
			counselorData.value.consultantId = selectedCounselor.id;
		}

		// 准备提交的数据，只包含后端需要的字段
		const submitData = {
			id: counselorData.value.id,
			chargeSort: counselorData.value.chargeSort,
			chargePrice: parseFloat(counselorData.value.chargePrice),
			consultantId: counselorData.value.consultantId,
			del: 0
		};

		// 验证必要字段
		if (!submitData.chargeSort || !submitData.chargePrice ||  !submitData.consultantId) {
			ElMessage.error('请完整填写所有必填字段');
			return;
		}
		if (counselorData.value.id) {
			axios.put(`/chargeStandard/${counselorData.value.id}`,counselorData.value )
				.then((resp) => {
					if (resp.includes('成功')) {
						ElMessage.success('修改成功');
						dialogFormVisible.value = false
						queryDataList()
					} else {
						ElMessage.error('修改失败: ' + (resp.message || ''));
					}
					queryDataList();
					dialogFormVisible.value = false;
				})
				.catch(error => {
					ElMessage.error('修改请求失败: ' + error.message);
				});
		} else {
			axios.post('/chargeStandard', counselorData.value)
				.then((resp) => {
					if (resp.includes('成功')) {
						ElMessage.success('新增成功');
					} else {
						ElMessage.error('新增失败: ' + (resp.message || ''));
					}
					queryDataList();
					dialogFormVisible.value = false;
				})
				.catch(error => {
					ElMessage.error('新增请求失败: ' + error.message);
				});
		}
	};

	const add = () => {
		title.value = '新增收费标准'
		cancle(); // 重置表单数据  
		dialogFormVisible.value = true;
		chooseOptions()
		fetchOptions()
	}

	const edit = (row) => {
		title.value = '编辑收费标准'
		dialogFormVisible.value = true
		counselorData.value = row

	}


	const remove = (id) => {
		ElMessageBox.confirm('此操作永久删除该文件，是否继续？', '提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			},
		).then(() => {
			axios.delete(`/chargeStandard/${id}`)
				.then(resp => {
					if (resp.includes('成功')) {
						ElMessage.success('删除成功')
						queryDataList()
					} else {
						ElMessage.error('删除失败')
					}
					queryDataList();
				})
		}).catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
	}

	const batchRemove = () => {
		ElMessageBox.confirm('此操作永久删除该文件，是否继续？', '提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			},
		).then(() => {
			axios.delete(`chargeStandard`, {
				params: {
					ids: multipleSelection.value.join(',')
				},
			})
				.then(resp => {
					if (resp.includes('成功')) {
						ElMessage.success('删除成功')
					} else {
						ElMessage.error('删除失败')
					}
					queryDataList();
					fetchOptions();
					chooseOptions();
				})
		}).catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
	}
</script>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-breadcrumb {
		margin-bottom: 15px;
		padding: 0 0 15px;
		border-bottom: 1px solid #ddd;
	}

	.el-pagination {
		margin-top: 15px;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}
</style>